﻿window.$jscript.fn.pc = (function () {
    var __FN = function () {
        return new __FN.fn._init();
    };
    var hxt = window.$jscript.fn;
    __FN.fn = __FN.prototype = {
        _init: function () { return this; },
        param: { optor: '', link: '' },
        ready: function (options) {
            var self = this;
            var optor = JSON.parse(hxt.fromBase64(options.optor)) || {};
            self.setStore(optor);
            hxt.ready({ link: options.link, reqType: 0, key: options.key });
            ELEMENT.Dialog.props.modalAppendToBody.default = false;
            ELEMENT.Drawer.props.modalAppendToBody.default = false;
            self.initPage();
        },
        setStore: function (optor) {
            var self = this;
            optor = optor || {};
            if (!hxt.isArray(optor.uiAccessList)) optor.uiAccessList = [];
            optor.canDo = function (access) {
                var _optor = optor, cando = false;
                access = $.trim('' + access);

                if (access.indexOf('|') >= 0) {
                    $.each(access.split('|'), function (idx, item) {
                        var funcId = $.trim(item);
                        if (funcId.length > 0) {
                            cando = !!_optor.uiAccessList.find(function (im) { return '' + im.flId == funcId; });
                            if (cando) return false;
                        }
                    });
                }
                else if (access.indexOf('&') >= 0) {
                    $.each(access.split('&'), function (idx, item) {
                        var funcId = $.trim(item);
                        if (funcId.length > 0) {
                            cando = !!_optor.uiAccessList.find(function (im) { return '' + im.flId == funcId; });
                            if (!cando) return false;
                        }
                    });
                }
                else {
                    cando = !!_optor.uiAccessList.find(function (im) { return '' + im.flId == access; });
                }
                return cando;
            };
            hxt.store = Vue.observable({
                optor: optor
            });
            //console.log(optor, 'optor');
            self.routeMapsDo();
        },
        Tabs: [
            { name: "菜单", path: "/menu", component: 'menu' },
            { name: "主页", path: "/main", component: 'main' }
        ],
        getRoutePath: function (path) {
            var x = { path: '' + path, root: '' };
            var arr = x.path.split('/');
            if (arr.length > 2) x.root = '/' + arr[1];
            else x.root = x.path;
            return x;
        },
        getComponent: function (uri, name) {
            //console.log(hxt.config, " hxt.config.link ");
            return function () { return hxt.getComponent({ url: hxt.config.link + uri, name: name }); };
        },
        routeMaps: null,
        routeMapsDo: function () {
            var self = this, optor = hxt.store.optor, maps = {};
            maps = {
                //#region 数据中心
                /*==组织架构==*/
                201: {
                    uri: 'pc/vueComponent', component: 'bill/engineOil',
                    props: function (route) {
                        return { bid: route.query.bid }
                    }
                }, //机油列表
                202: { uri: 'pc/vueComponent', component: 'bill/bill' }, //账单
                401: { uri: 'pc/vueComponent', component: 'Foley/img' }, //图片集
                402: { uri: 'pc/vueComponent', component: 'Foley/video' }, //视频集
                403: { uri: 'pc/vueComponent', component: 'Foley/mediaTitle' }, //媒体头
                404: { uri: 'pc/vueComponent', component: 'Foley/card' }, //图文卡片
                305: { uri: 'pc/vueComponent', component: 'My/test' }, //视频集
                306: { uri: 'pc/vueComponent', component: 'My/fingerPrint' }, //用户
                999: { uri: 'pc/vueComponent', component: 'My/fun' }, //权限
                307: { uri: 'pc/vueComponent', component: 'My/wangeditor' }, //富文本
                308: { uri: 'pc/vueComponent', component: 'My/notice' }, //公告
                309: { uri: 'pc/vueComponent', component: 'My/document' }, //文档
                3011: { uri: 'pc/vueComponent', component: 'My/menstruation' }, //姨妈助手
                501: { uri: 'pc/vueComponent', component: '' }, //这个存在的意义 ：50101>502 所以日程菜单的索引在课程的后面 这个可把日程的索引在课程的前面
                50101: { uri: 'pc/vueComponent', component: 'app/schedule/list' }, //日程列表
                50102: { uri: 'pc/vueComponent', component: 'app/schedule/schedule' }, //日程管理
                502: { uri: 'pc/vueComponent', component: 'app/scCACourse' }, //课程

                901: { uri: 'pc/vueComponent', component: 'develop/proc' }, //存储过程
            };
            self.routeMaps = maps;
        },
        initPage: function () {
            var self = this, optor = hxt.store.optor, menuList = [], routes = [];
            var createRoute = function (m) {
                var getComponent = function (uri, name) { return function () { return hxt.getComponent({ url: hxt.config.link + uri, name: name }); }; }
                    , r = {
                        name: ('' + m.id),
                        path: m.path,
                        meta: { menu: m, child: [] },
                        redirect: undefined,
                        component: { template: '<el-empty description="' + m.name + '"></el-empty>' },
                        children: []
                    }
                    , rmap = self.routeMaps[r.name];
                if (!!rmap) {
                    r.component = getComponent(rmap.uri, rmap.component);
                    if (!!rmap.props) r.props = rmap.props;
                    if (!!rmap.child && rmap.child.length > 0) {
                        if (!!rmap.redirect) r.redirect = '{0}/{1}'.formatStr(m.path, rmap.child[0].path);
                        rmap.child.map(function (v) {
                            var rc = { path: v.path + (!!v.param ? v.param : ''), meta: r.meta, component: getComponent(v.uri, v.component) };
                            if (!!v.props) rc.props = v.props;
                            if (!!v.root) rc.name = m.path + '/' + v.path;
                            r.children.push(rc);

                            r.meta.child.push({ name: v.desc, path: m.path + '/' + v.path, index: v.index });
                        });
                    }
                }
                else {
                    r.component = getComponent(hxt.config.link + 'pc/vueComponent', m.state);
                }
                return r;
            };
            var _realList = [];
            var getParent = function (o) {
                if (!_realList.find(function (item) { return item.flId == o.flId; })) {
                    _realList.push(o);
                }
                var p = optor.uiAccessList.find(function (item) {
                    return item.flId == o.flpId;
                });
                if (!!p) {
                    getParent(p);
                }
            };
            //管理员 仅生成已实现的菜单
            $.grep(optor.uiAccessList, function (item, ix) {
                return !!self.routeMaps[item.flId] && item.show != 2 && item.show != 99;
            }).map(function (item) {
                getParent(item);
            });

            var createMenu = function (pId, list) {
                var arr = $.grep(_realList, function (item, ix) {
                    return item.flpId == pId;
                });
                $.each(arr, function (ix, item) {
                    var m = {
                        id: item.flId, pId: item.flpId, level: item.level, name: item.flName, state: item.state, path: '/' + item.flId, children: []
                    };
                    if (m.level == 2) {
                        routes.push(createRoute(m));
                    }
                    createMenu(m.id, m.children);
                    list.push(m);
                });
            };
            createMenu(1, menuList);
            //console.log(optor, 'menuList');
            routes.push({
                path: '/menu', component: {
                    name: 'menu',
                    template: $('#_MenuTpl').html(),
                    computed: {
                        menuList: function () {
                            return !!this.$root ? this.$root.menuList : [];
                        }
                    },
                    methods: {
                        isThird: function (m) {
                            return !!this.$root && this.$root.isThird(m);
                        }
                    }
                }
            });
            routes.push({
                path: '/main', component: function () {
                    return hxt.getComponent({ url: hxt.config.link + 'pc/vueComponent', name: 'main' });
                }
            });
            routes.push({ path: '/', redirect: "/main" });
            routes.push({ path: '/nofunc', component: { template: '<el-empty description="未授权此操作"></el-empty>' } });
            routes.push({ path: "*", component: { template: '<el-empty description="页面不存在"></el-empty>' } });

            var router = new VueRouter({
                routes: routes
            });
            router.beforeEach(function (to, from, next) {
                var vn = self.getRoutePath(to.path);
                if (vn.path.indexOf('/ynupper') == 0) {
                    return false;
                }
                if (vn.root == vn.path) { //一级地址
                    //查找是否有相同 root 的二级地址
                    var mu = self.Tabs.find(function (item) {
                        var mn = self.getRoutePath(item.path);
                        return mn.root != mn.path && mn.root == vn.root;
                    });
                    if (!!mu) {
                        if (from.path == mu.path) return false;
                        router.push(mu.path);
                        return false;
                    }
                }
                next();
            });
            //指令 v-blur 使 el-button 点击后失去焦点
            Vue.use({
                install: function (app) {
                    var fun = function (e) {
                        var target = e.target;
                        if (target.nodeName == "SPAN" || target.nodeName == "I") {
                            target = e.target.parentNode;
                        }
                        target.blur();
                    };
                    app.directive('blur', {
                        inserted: function (el) {
                            el.addEventListener('click', fun, true);
                        },
                        unbind: function (el) {
                            el.removeEventListener('click', fun)
                        }
                    });
                }
            });

            hxt.element.elVue = new Vue({
                router: router,
                data: function () {
                    var _this = this;
                    return {
                        optor: optor,
                        isCollapse: false,
                        tabs: self.Tabs,
                        menuList: menuList,

                        //#region 我的
                        showUser: false,
                        showTag: -1,
                        userList: [],
                        vercode: { code: 0, text: '' },
                        lo: { account: '', pwd: '', uiType: -1, code: '' },
                        loRules: {
                            account: [
                                { required: true, message: '请输入账号' },
                                {
                                    validator: function (rule, value, callback) {
                                        if (value.length < 5) return callback(new Error('请输入有效的账号'));
                                        callback();
                                    }
                                }
                            ],
                            pwd: [
                                { required: true, message: '请输入密码' },
                                {
                                    validator: function (rule, value, callback) {
                                        if (value.length < 4) return callback(new Error('请输入有效的密码'));
                                        callback();
                                    }
                                }
                            ],
                            code: [
                                { required: true, message: '请输入验证码' },
                                {
                                    validator: function (rule, value, callback) {
                                        if (value != _this.vercode.code) return callback(new Error('验证码不正确'));
                                        callback();
                                    }
                                }
                            ]
                        },

                        obj: {
                            oldPwd: '',
                            newPwd: '',
                            confirmPwd: ''
                        },
                        objRules: {
                            oldPwd: [
                                { required: true, message: '请输入旧密码' },
                                {
                                    validator: function (rule, value, callback) {
                                        if (value.length < 4) return callback(new Error('旧密码不正确'));
                                        callback();
                                    }
                                }
                            ],
                            newPwd: [
                                { required: true, message: '请输入新密码' },
                                {
                                    validator: function (rule, value, callback) {
                                        if (value == _this.obj.oldPwd) return callback(new Error('新密码与旧密码不能相同'));
                                        if (value.length < 4) return callback(new Error('密码至少4位'));
                                        if (value.length > 16) return callback(new Error('密码最多16位'));
                                        if (!/^[a-zA-Z0-9\(\)\[\]\{\}\/\\\*\+\.\?\^\$\|~!@#%&=]{4,16}$/.test(value)) return callback(new Error('密码只能包含数字、字母或()[]{}/\*.?^$~!@#%&=|'));
                                        callback();
                                    }
                                }
                            ],
                            confirmPwd: [
                                { required: true, message: '请重复输入新密码' },
                                {
                                    validator: function (rule, value, callback) {
                                        if (_this.obj.newPwd != value) return callback(new Error('新密码不一致'));
                                        callback();
                                    }
                                }
                            ]
                        },

                        userInfo: {
                            uiSex: -1,
                            uiName: '',
                            uiParentName: '',
                            emailList: [],
                            phoneList: [],

                            uiAccount: null,
                            smsPhone: null,

                        },
                        userRules: {
                            uiSex: [
                                { required: true, message: '请选择性别' },
                            ],
                            uiName: [
                                { required: true, message: '请输入姓名' },
                                {
                                    validator: function (rule, value, callback) {
                                        if (value.length > 16) return callback(new Error('姓名限16字以内'));
                                        callback();
                                    }
                                }
                            ],
                            uiParentName: [
                                { required: true, message: '请输入家长姓名' },
                                {
                                    validator: function (rule, value, callback) {
                                        if (value.length > 32) return callback(new Error('家长姓名限32字以内'));
                                        callback();
                                    }
                                }
                            ],
                            emailList: [
                                {
                                    validator: function (rule, value, callback) {
                                        var err = '', emailList = _this.userInfo.emailList;
                                        $.each(emailList, function (idx, item) {
                                            if (!item.uelEmail) {
                                                err = '第{0}项邮件地址不能为空'.formatStr(idx + 1);
                                                return false;
                                            } else if (!hxt.isEmail(item.uelEmail)) {
                                                err = '第{0}项不是有效的邮件地址'.formatStr(idx + 1);
                                                return false;
                                            }
                                        });
                                        if (!!err) return callback(new Error(err));
                                        callback();
                                    }
                                }
                            ],
                            phoneList: [
                                {
                                    validator: function (rule, value, callback) {
                                        var err = '', phoneList = _this.userInfo.phoneList;
                                        $.each(phoneList, function (idx, item) {
                                            if (!item.uplPhoneNumber) {
                                                err = '第{0}项联系电话不能为空'.formatStr(idx + 1);
                                                return false;
                                            } else if (hxt.getPhoneType(item.uplPhoneNumber) == -1) {
                                                err = '第{0}项不是有效的号码'.formatStr(idx + 1);
                                                return false;
                                            }
                                        });
                                        if (!!err) return callback(new Error(err));
                                        callback();
                                    }
                                }
                            ],
                        },
                        //#endregion

                    };
                },
                watch: {
                    '$route': {
                        handler: function (val) {
                            var _this = this, vn = self.getRoutePath(val.path), menu = val.meta.menu;
                            if (!!menu) {
                                var mu = _this.tabs.find(function (item) {
                                    var mn = self.getRoutePath(item.path);
                                    return mn.root != '/' && mn.root == vn.root;
                                });
                                if (!!mu) mu.path = vn.path;
                                else _this.tabs.push({ name: menu.name, path: vn.path, component: '' + (optor.uiType == 3 ? menu.id : menu.state) });
                            }
                        },
                        immediate: true
                    }
                },
                computed: {
                    now: function () {
                        return self.getRoutePath(this.$route.path);
                    }
                },
                mounted: function () {
                    //console.log(this.tabs);                    
                },
                methods: {
                    handleClick: function (tab, event) {
                        var _this = this;
                        //console.log(_this.$route.path , tab.name); 
                        if (_this.$route.path != tab.name) _this.$router.push(tab.name);
                    },
                    removeTab: function (name) {
                        //console.log(name, this.now);
                        var _this = this;
                        if (_this.tabs.length == 1) return hxt.msg("再关就没啦~", null, null, "warning");
                        var idx = _this.tabs.findIndex(function (item) {
                            return item.path == name;
                        });
                        if (idx >= 0) _this.tabs.splice(idx, 1);
                        //关闭选中的
                        if (_this.now.path == name) {
                            var m = _this.tabs[idx];
                            if (!m) m = _this.tabs[idx - 1];
                            if (!!m) _this.$router.push(m.path);
                        }
                    },
                    isThird: function (m) {
                        return !!m && ('' + m.state).indexOf('ynupper') == 0;
                    },
                    logoff: function () {
                        window.location.replace('Login');
                    },
                    stop: function () { },

                    //#region 我的
                    menuEvent: function (e) {
                        var _this = this;
                        if (e == 'accountSwitches') _this.accountSwitches();
                        else if (e == 'securitySettings') _this.securitySettings();
                        else if (e == 'personalInfo') _this.personalInfo();
                    },
                    changecode: function () {
                        this.vercode = hxt.createNumCode();
                        this.lo.code = '';
                    },
                    accountSwitches: function () {
                        var _this = this;
                        _this.showTag = 1;
                        _this.getUserForMain();
                        _this.showUser = true;
                        _this.changecode();
                    },
                    getUserForMain: function () {
                        var _this = this;
                        _this.userList = [];
                        hxt.post({
                            url: hxt.config.link + 'pc/getUserInfoForMain',
                            data: {},
                            ok: function (res) {
                                if (res.code != 0) return hxt.error('加载关联用户列表失败：' + res.errmsg);

                                _this.userList = res.data;
                            }
                        });
                    },
                    out: function (item, index) {
                        var _this = this;
                        hxt.confirm('确定要取消关联{0}？'.formatStr(item.uiName), function () {
                            hxt.post({
                                url: hxt.config.link + 'pc/getUnRelatedMain',
                                data: { uiId: item.uiId },
                                ok: function (res) {
                                    if (res.code != 0) return hxt.error('取消关联失败：' + res.errmsg);

                                    _this.userList.splice(index, 1);
                                    hxt.success('取消关联成功');
                                }
                            });
                        });
                    },
                    switchUser: function (item) {
                        var _this = this;
                        hxt.post({
                            url: hxt.config.link + 'pc/toNewUser',
                            data: item,
                            ok: function (res) {
                                if (res.code != 0) return hxt.error('切换失败：' + res.errmsg);

                                hxt.success('切换成功');
                                window.location.replace(res.data.url);
                            }
                        });

                    },
                    association: function () {
                        var _this = this;
                        hxt.validateElForm(_this, "lo", function () {
                            hxt.post({
                                url: hxt.config.link + 'pc/getRelatedMainByAccount',
                                data: _this.lo,
                                ok: function (res) {
                                    if (res.code != 0) {
                                        if (res.code == 1) _this.lo.uiType = 0;
                                        return hxt.error('关联失败：' + res.errmsg);
                                    }

                                    _this.getUserForMain();
                                    hxt.success('关联成功');
                                }
                            });
                        });
                    },
                    securitySettings: function () {
                        var _this = this;
                        _this.showTag = 2;
                        _this.showUser = true;
                    },
                    editPwd: function () {
                        var _this = this;
                        hxt.validateElForm(_this, "objForm", function () {
                            hxt.post({
                                url: hxt.config.link + 'pc/getUserChangePwd',
                                data: _this.obj,
                                ok: function (res) {
                                    if (res.code != 0) return hxt.error('修改密码失败：' + res.errmsg);

                                    hxt.success('您修改密码已成功，请在下次登录时使用新密码登录');
                                    _this.closeUser();
                                }
                            });
                        });
                    },
                    personalInfo: function () {
                        var _this = this;
                        _this.userRules = _this.optor.uiType == 1 ? {
                            uiSex: [
                                { required: true, message: '请选择性别' },
                            ],
                            uiName: [
                                { required: true, message: '请输入姓名' },
                                {
                                    validator: function (rule, value, callback) {
                                        if (value.length > 16) return callback(new Error('姓名限16字以内'));
                                        callback();
                                    }
                                }
                            ],
                            uiParentName: [
                                { required: true, message: '请输入家长姓名' },
                                {
                                    validator: function (rule, value, callback) {
                                        if (value.length > 32) return callback(new Error('家长姓名限32字以内'));
                                        callback();
                                    }
                                }
                            ],
                            emailList: [
                                {
                                    validator: function (rule, value, callback) {
                                        var err = '', emailList = _this.userInfo.emailList;
                                        $.each(emailList, function (idx, item) {
                                            if (!item.uelEmail) {
                                                err = '第{0}项邮件地址不能为空'.formatStr(idx + 1);
                                                return false;
                                            } else if (!hxt.isEmail(item.uelEmail)) {
                                                err = '第{0}项不是有效的邮件地址'.formatStr(idx + 1);
                                                return false;
                                            }
                                        });
                                        if (!!err) return callback(new Error(err));
                                        callback();
                                    }
                                }
                            ],
                            phoneList: [
                                {
                                    validator: function (rule, value, callback) {
                                        var err = '', phoneList = _this.userInfo.phoneList;
                                        $.each(phoneList, function (idx, item) {
                                            if (!item.uplPhoneNumber) {
                                                err = '第{0}项联系电话不能为空'.formatStr(idx + 1);
                                                return false;
                                            } else if (hxt.getPhoneType(item.uplPhoneNumber) == -1) {
                                                err = '第{0}项不是有效的号码'.formatStr(idx + 1);
                                                return false;
                                            }
                                        });
                                        if (!!err) return callback(new Error(err));
                                        callback();
                                    }
                                }
                            ],
                        } : _this.optor.uiType == 0 ? {
                            uiSex: [
                                { required: true, message: '请选择性别' },
                            ],
                            uiName: [
                                { required: true, message: '请输入姓名' },
                                {
                                    validator: function (rule, value, callback) {
                                        if (value.length > 16) return callback(new Error('姓名限16字以内'));
                                        callback();
                                    }
                                }
                            ],
                            emailList: [
                                {
                                    validator: function (rule, value, callback) {
                                        var err = '', emailList = _this.userInfo.emailList;
                                        $.each(emailList, function (idx, item) {
                                            if (!item.uelEmail) {
                                                err = '第{0}项邮件地址不能为空'.formatStr(idx + 1);
                                                return false;
                                            } else if (!hxt.isEmail(item.uelEmail)) {
                                                err = '第{0}项不是有效的邮件地址'.formatStr(idx + 1);
                                                return false;
                                            }
                                        });
                                        if (!!err) return callback(new Error(err));
                                        callback();
                                    }
                                }
                            ],
                            phoneList: [
                                {
                                    validator: function (rule, value, callback) {
                                        var err = '', phoneList = _this.userInfo.phoneList;
                                        $.each(phoneList, function (idx, item) {
                                            if (!item.uplPhoneNumber) {
                                                err = '第{0}项联系电话不能为空'.formatStr(idx + 1);
                                                return false;
                                            } else if (hxt.getPhoneType(item.uplPhoneNumber) == -1) {
                                                err = '第{0}项不是有效的号码'.formatStr(idx + 1);
                                                return false;
                                            }
                                        });
                                        if (!!err) return callback(new Error(err));
                                        callback();
                                    }
                                }
                            ],
                        } : {
                            emailList: [
                                {
                                    validator: function (rule, value, callback) {
                                        var err = '', emailList = _this.userInfo.emailList;
                                        $.each(emailList, function (idx, item) {
                                            if (!item.uelEmail) {
                                                err = '第{0}项邮件地址不能为空'.formatStr(idx + 1);
                                                return false;
                                            } else if (!hxt.isEmail(item.uelEmail)) {
                                                err = '第{0}项不是有效的邮件地址'.formatStr(idx + 1);
                                                return false;
                                            }
                                        });
                                        if (!!err) return callback(new Error(err));
                                        callback();
                                    }
                                }
                            ]
                        };

                        hxt.post({
                            url: hxt.config.link + 'pc/getUserInfo',
                            data: {},
                            ok: function (res) {
                                if (res.code != 0) return hxt.error('加载用户信息失败：' + res.errmsg);

                                _this.userInfo = res.data;

                                //if (_this.userInfo.phoneList.length == 0) _this.userInfo.phoneList.push({ uplPhoneNumber: '' });
                                //if (_this.userInfo.emailList.length == 0) _this.userInfo.emailList.push({ uelEmail: '' });
                            }
                        });
                        _this.showTag = 3;
                        _this.showUser = true;
                    },
                    editUserInfo: function () {
                        var _this = this;
                        var userInfo = JSON.parse(JSON.stringify(_this.userInfo));
                        userInfo.emailList = userInfo.emailList.map(function (item, idx) { return item.uelEmail; }).join(',');
                        userInfo.phoneList = userInfo.phoneList.map(function (item, idx) { return item.uplPhoneNumber; }).join(',');
                        hxt.validateElForm(_this, "userForm", function () {
                            hxt.post({
                                url: hxt.config.link + 'pc/getUserChangeInfo',
                                data: userInfo,
                                ok: function (res) {
                                    if (res.code != 0) return hxt.error('修改失败：' + res.errmsg);

                                    _this.optor.uiName = userInfo.uiName;
                                    hxt.success('修改成功');
                                    _this.closeUser();
                                }
                            });
                        });
                    },
                    editList: function (type, flag, index) {
                        var _this = this;
                        if (type == 1) {//联系电话
                            if (flag == 1) _this.userInfo.phoneList.push({ uplPhoneNumber: '' });
                            else _this.userInfo.phoneList.splice(index, 1);
                        } else if (type == 2) {//电子邮件
                            if (flag == 1) _this.userInfo.emailList.push({ uelEmail: '' });
                            else _this.userInfo.emailList.splice(index, 1);
                        }

                    },
                    closeUser: function () {
                        var _this = this;
                        _this.$nextTick(function () {
                            if (_this.showTag == 1) _this.$refs.lo.resetFields();
                            if (_this.showTag == 2) _this.$refs.objForm.resetFields();
                            if (_this.showTag == 3) _this.$refs.userForm.resetFields();
                        });
                        _this.showUser = false;
                    },
                    //#endregion 我的


                },
                components: {
                    schoolButton: function () { return hxt.staticComponent(self.param.components.schoolButton); }
                }
            }).$mount('#app');
        }
    };
    __FN.fn._init.prototype = __FN.fn;
    return __FN.fn;
})();